package juc;

public class Demo5 {

    public static void main(String[] args) {
        Goods2 goods = new Goods2();


        new Thread(()->{
            //店家线程
            System.out.println("店家线程：");
            //增加多个商品
            for(int i = 0 ; i < 3 ; i++){
                goods.addThisGoods();
            }

            System.out.println("店家新增好了！");
        },"restaurant").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程1：");
            goods.buyThisGoods();
            System.out.println("顾客1买好了！");
        },"customer1").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程2：");
            goods.buyThisGoods();
            System.out.println("顾客2买好了！");
        },"customer2").start();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程3：");
            goods.buyThisGoods();
            System.out.println("顾客3买好了！");
        },"customer3").start();


    }
}

class Goods2{
    private String name = "商品1";
    /**
     * 库存
     */
    private int count = 0;

    public synchronized void buyThisGoods() {
        while (count==0){
            try {
                //库存为0，等待
                System.out.println("buyThisGoods等待");
                this.wait();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //库存不为0，商品库存减1
        count--;
        System.out.println("buyThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
        //通知其他线程
        this.notifyAll();
    }

    public synchronized void addThisGoods(){
        count++;
        System.out.println("addThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
        //通知其他线程
        this.notifyAll();
    }
}